package com.bang.concurrency.example.concurrent;

import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.*;

/**
 * @Auther: Bang
 * @Date: 2019/10/3 22:13
 * @Description: TreeSet 高并发安全版本
 */
@ThreadSafe
@Slf4j
public class ConcurrentSkipListSetExample {


    private static int threadCount = 200;

    private static int clientCount = 5000;

    private static Set<Integer> set = new ConcurrentSkipListSet<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        final CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for (int i = 0; i < clientCount; i++) {
            final int count = i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    update(count);
                    semaphore.release();
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    log.error("e:{}", e);
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.error("size={}", set.size());
    }

    private static void update(int count) {
        set.add(count);
    }
}
